package com.keter.framework.web.component.handler;

import com.alibaba.fastjson.JSONObject;
import com.keter.framework.core.exception.ValidateException;
import com.keter.framework.core.result.JSONResult;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
  private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

  /* 配置模式 */
  @Value("${spring.profiles.active:dev}")
  private String pofile;

  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public JSONResult resolveException(HttpServletRequest req, Exception ex) {
    JSONResult errorObj = new JSONResult();
    errorObj.put(JSONResult.KEY_STATUS, JSONResult.Status.ERROR.value());
    // 保持一致的返回结果
    errorObj.put(JSONResult.KEY_DATA, new JSONObject());

    // 出错时记录请求URI，便于排查问题
    errorObj.put(JSONResult.KEY_ERROR, "path= "+req.getRequestURI()+" , message= "+ex.getMessage());
    // 开发或持续集成模式下在前台显示错误堆栈详细信息
    if("dev".equalsIgnoreCase(pofile)||"ci".equalsIgnoreCase(pofile)) {
      errorObj.put(JSONResult.KEY_CAUSE, ExceptionUtils.getStackTrace(ex));
    }
    if (ex instanceof ValidateException) {
      logger.error("校验异常:{}, msg:{}, cause:{}",req.getRequestURI(), ex.getMessage(),ex.getCause());
      errorObj.put(JSONResult.KEY_CODE,((ValidateException) ex).getCode());
      return errorObj;
    } else {
      logger.error("请求异常: {}",req.getRequestURI(),ex);
      errorObj.put(JSONResult.KEY_CODE, ValidateException.Errors.OTHER.value());
    }
    return errorObj;
  }
}
